/*
 * private-8.c
 * Back-end for 8bit data operations
 *
 *  Created on: Sep 28, 2009
 *      Author: Orlando Arias
 *	   License: GPLv3
 *
 *   libHD44780 for Arduino systems.
 *   Copyright (C) 2009  Orlando Arias
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "WProgram.h"
#include "common/common_private.h"

#include "private-8.h"

uint8_t lcd8_getRaw(LCD8 *l, uint8_t rs_state){
	// prepare return value and data fetch operation
	uint8_t retVal = 0;
	digitalWrite(l->rs_pin, rs_state);
	digitalWrite(l->rw_pin, HIGH);
	delayMicroseconds(1);			// must wait 40 ns before driving strobe high

	// set up strobe and wait for data to settle
	digitalWrite(l->strobe, HIGH);
	delayMicroseconds(1);			// must wait 160 ns before data is available

	// get data and store it under return value
	for (uint8_t i = 0; i<8; i++){
		pinMode(l->datapin[i], INPUT);
		retVal <<= 1;
		retVal |= (digitalRead(l->datapin[7-i]));
		// The above two statements should refit the following
		// commented statement.
		//retVal |= (digitalRead(l->datapin[i]) << i);
		pinMode(l->datapin[i], OUTPUT);
	}

	// finish pulse
	digitalWrite(l->strobe, LOW);

	return retVal;
}

void lcd8_sendRaw(LCD8 *l, uint8_t data, uint8_t rs_state){
	// prepare to send data
	digitalWrite(l->rs_pin, rs_state);
	digitalWrite(l->rw_pin, LOW);

	// write data
	lcd8_writeByte(l, data);

	// commit data
	lcd_triggerStrobe(l->strobe);
}

void lcd8_writeByte(LCD8 *l, uint8_t byte){
	for (uint8_t i = 0; i< 8; i++){
		digitalWrite(l->datapin[i], byte & 0x01);
		byte >>= 1;
	}
}
